<template>
  <div class="editor-header">
    <div class="left">
      <div class="back" @click="back">
        <SvgIcon icon-class="ic_返回" />
        <span>返回</span>
      </div>
      <el-input
        v-if="sceneStore.sceneDetail"
        class="scene-name"
        v-model="sceneStore.sceneDetail.activityName"
        :disabled="activityNameEdit"
        :maxlength="50"
      >
        <template #suffix>
          <SvgIcon
            :icon-class="activityNameEdit ? 'ic_编辑' : 'ic_确认'"
            @click="activityNameEdit = !activityNameEdit"
          />
        </template>
      </el-input>
      <el-button
        class="onlineMapBtn"
        type="info"
        :class="sceneStore.mapPanelVisible ? 'active' : ''"
        @click="toggleMapPanelVisible"
      >
        <span>在线地图</span>
        <template #icon>
          <SvgIcon icon-class="ic_在线地图" />
        </template>
      </el-button>
    </div>
    <div class="right">
      <el-popover placement="bottom" :width="280" popper-class="version-popover">
        <template #reference>
          <el-button type="info">
            <span>版本记录</span>
            <template #icon>
              <SvgIcon icon-class="ic_版本记录" />
            </template>
          </el-button>
        </template>
        <div class="version-wrap">
          <div class="version-header">版本记录</div>
          <div class="version-content">
            <ul class="version-ul">
              <li class="version-li li-header">
                <div class="version-name">保存时间</div>
                <div class="version-ope">操作</div>
              </li>
              <li class="version-li" v-for="list in sceneStore.versionList" :key="list.conifgId">
                <div class="version-name">
                  {{ dayjs(list.createTime).format('YYYY年MM月DD日 HH:mm:ss') }}
                </div>
                <div
                  v-if="list.conifgId !== sceneStore.sceneDetail?.conifgId"
                  class="version-ope"
                  @click="viewVersion(list)"
                >
                  查看
                </div>
              </li>
            </ul>
          </div>
        </div>
      </el-popover>

      <el-button type="info" @click="onRelease">
        <span>发布</span>
        <template #icon>
          <SvgIcon icon-class="ic_发布" />
        </template>
      </el-button>
      <el-button type="info" @click="togglePreview">
        <span>预览</span>
        <template #icon>
          <SvgIcon icon-class="ic_预览" />
        </template>
      </el-button>
      <el-button type="primary" @click="save">
        <span>保存</span>
        <template #icon>
          <SvgIcon icon-class="ic_保存" />
        </template>
      </el-button>
    </div>
  </div>
  <!-- 首次保存 -->
  <SceneFirstSaveDialog v-if="sceneFirstSaveVisible" @close-handle="sceneFirstSaveClose" />
</template>

<script setup lang="ts">
import { saveSceneConfig, updateScene, getSceneDetail } from '@/api/scene';
import { operateInvalidPoi } from '@/service';
import { useSceneStore } from '@/store/scene';
import { flattenTreeIterative, setTreeSortField } from '@/utils';
import { messageUtil } from '@jl/element-plus/utils';
import { dayjs } from 'element-plus';
import { cloneDeep } from 'lodash';
import { useRouter } from 'vue-router';
import SceneFirstSaveDialog from './scene-first-save/index.vue';
import { useRequest } from '@jl/common/composable';

defineOptions({
  name: '',
});

interface IProps {
  activityId: string;
}

const props = withDefaults(defineProps<IProps>(), {
  activityId: '',
});
const emits = defineEmits(['release']);
const { run: basicDetailRun, data: basicDetailData } = useRequest<any, API.Scene.Scene | null>(
  getSceneDetail,
  null
);

const router = useRouter();
const sceneStore = useSceneStore();
const activityNameEdit = ref<boolean>(true);
const sceneFirstSaveVisible = ref<boolean>(false);

const toggleMapPanelVisible = () => {
  sceneStore.mapPanelVisible = !sceneStore.mapPanelVisible;
};

const togglePreview = () => {
  sceneStore.preview = !sceneStore.preview;
};

function back() {
  router.push({ path: `/scene/list` });
}

async function save() {
  const { cimInstance } = window;
  if (!sceneStore.sceneDetail) return;
  // 判断是否首次保存
  const detailConfigJson: any = sceneStore.sceneDetail.configJson
    ? JSON.parse(sceneStore.sceneDetail.configJson)
    : null;
  if (!detailConfigJson || !detailConfigJson.cimup) {
    sceneFirstSaveVisible.value = true;
    return;
  }
  if (!sceneStore.sceneDetail.activityName) {
    messageUtil.warning('场景名称不能为空，请修正后再保存');
    return;
  }
  await saveBasic();
  console.log('场景导出参数-------------------', cimInstance.api.exportCurrentScene());

  console.log('数结构', sceneStore.layerTree);
  operateInvalidPoi();
  const layerTree = cloneDeep(sceneStore.layerTree);
  // 设置排序字段
  setTreeSortField(layerTree);
  console.log('---------setTreeSortField--------', layerTree);
  const layerList = flattenTreeIterative(layerTree);
  for (const list of layerList) {
    if (!list.name) {
      messageUtil.warning('图层名称不能为空，请修正后再保存');
      return;
    }
    // 除了div,后续属性不再存储
    if (!['div'].includes(list.type)) {
      list.attr = null;
      delete list.attr;
    }
    if (list.attr) {
      if (list.attr.position) {
        list.attr.position = list.attr.position.map((v: any) => Number(v));
      }
    }
    if (list?.json?.hasOwnProperty('zoomTo')) {
      delete list?.json.zoomTo;
    }
  }

  const configJson = {
    cimup: cimInstance.api.exportCurrentScene(),
    layer: layerList,
  };

  const formData = new FormData();
  formData.append('activityId', props.activityId);
  formData.append('configJson', JSON.stringify(configJson));
  saveSceneConfig({ data: formData }).then((res) => {
    messageUtil.success('保存成功');
    sceneStore.getVersionList();
  });
}

async function saveBasic() {
  if (!sceneStore.sceneDetail) return;
  const fData = new FormData();
  fData.set('activityId', sceneStore.sceneDetail.activityId);
  fData.set('activityName', sceneStore.sceneDetail.activityName);
  fData.set('projectId', sceneStore.sceneDetail.projectId || '');
  fData.set('actViewAngle', sceneStore.sceneDetail.actViewAngle || '');
  fData.set('actDesp', sceneStore.sceneDetail.actDesp || '');
  fData.set('actCover', sceneStore.sceneDetail.actCover || '');
  fData.set('conifgId', sceneStore.sceneDetail.conifgId || '');
  const param = {
    data: fData,
  };
  await updateScene(param);
}

function viewVersion(list: API.Scene.IVersion) {
  router.push({ path: `/scene/version/${list.activityId}/${list.conifgId}` });
}

function onRelease() {
  emits('release');
}

async function sceneFirstSaveClose(flag: any) {
  sceneFirstSaveVisible.value = false;
  if (flag) {
    await basicDetailRun({ params: { activityId: sceneStore.sceneDetail.activityId } });
    sceneStore.sceneDetail = basicDetailData.value;
  }
}
</script>

<style lang="less">
.version-popover {
  padding: 0px !important;
  .version-wrap {
    position: relative;
    max-height: calc(100vh - 100px);
    overflow-y: auto;

    .version-header {
      height: 30px;
      line-height: 30px;
      padding: 0 20px;
      border-bottom: 1px solid rgba(154, 154, 154, 0.08);
    }
    .version-content {
      padding: 10px;
      .version-ul {
        .version-li {
          height: 28px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-radius: 4px;
          padding: 0 10px;
          margin-bottom: 4px;
          .version-name {
            color: #161616;
          }
          .version-ope {
            color: #0560fd;
            cursor: pointer;
          }
          &.li-header {
            font-size: 14px;
            font-weight: 400;
            color: #585858;
            .version-ope {
              color: #585858;
              cursor: default;
            }
          }
          &:last-child {
            margin-bottom: 0px;
          }
          &:not([class$='li-header']):hover {
            background: rgba(5, 96, 253, 0.2);
          }
        }
      }
    }
  }
}
</style>
<style lang="less" scoped>
.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  background: #1d1e1f;
  border-bottom: 2px solid #000000;
  pointer-events: initial;
  .el-button {
    height: 36px;
  }

  .left {
    display: flex;
    align-items: center;
    width: 30%;
    .back {
      display: flex;
      align-items: center;
      white-space: nowrap;
      margin-right: 16px;
      cursor: pointer;
      .svg-icon {
        margin-left: 12px;
        margin-right: 4px;
        font-size: 20px;
      }
    }
    .scene-name {
      width: 326px;
      height: 36px;
      :deep(.el-input__wrapper) {
        background: #242c34;
        border-radius: 4px;
        box-shadow: none;
        padding-right: 44px;
        .el-input__inner {
          color: #fff;
        }
        .el-input__suffix {
          position: absolute;
          right: 14px;
          pointer-events: auto;
          cursor: pointer;
        }
        .svg-icon {
          margin-left: 0;
          margin-right: 0;
          font-size: 24px;
        }
      }
    }
    .onlineMapBtn {
      margin-left: 10px;

      &:hover {
        background: #0560fd;
        border: 1px solid #0560fd;
      }
      &.active {
        background: #0560fd;
        border: 1px solid #0560fd;
      }
    }
    .globalEffect-btn {
      margin-left: 10px;

      &:hover {
        background: #0560fd;
        border: 1px solid #0560fd;
      }

      &.active {
        background: #0560fd;
        border: 1px solid #0560fd;
      }
    }
  }

  .right {
    display: flex;
    justify-content: flex-end;
    width: 30%;
    padding-right: 20px;
  }
  :deep(.el-button + .el-button) {
    margin-left: 10px;
  }
  :deep(.el-icon) {
    width: 24px;
    height: 24px;
    .svg-icon {
      font-size: 24px;
    }
  }
}
</style>
